package com.cn.icss.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cn.icss.service.IRewardService;
import com.cn.icss.utils.HttpOkUtils;
import com.cn.icss.vo.GiftScoreRef;
import com.cn.icss.vo.TargetGiftRef;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @中软华腾软件系统有限公司,未经授权不得擅自传播
 * @类描述: 打赏业务实现类
 * @类名称:RewardServiceImpl
 * @作者: Administrator
 * @编辑时间: 2020/05/13 15:41
 * @版本: 1.0
 */
public class RewardServiceImpl implements IRewardService {

    private GiftScoreRef giftScoreDao = new GiftScoreRef().dao();
    private TargetGiftRef targetRefGiftDao = new TargetGiftRef().dao();

    @Override
    public List<GiftScoreRef> findAllGift() {
        return giftScoreDao.findAll();
    }

    @Override
    public boolean exceptional(String targetId, String userId, String userName,String giftId) {

        // 1. 使用giftid查询出name与score
        GiftScoreRef giftScore = giftScoreDao.findFirst("SELECT * FROM gift_score_ref WHERE giftId= ? ", giftId);
        TargetGiftRef targetRefGift = new TargetGiftRef();
        Date now = new Date();
        targetRefGift.setId(UUID.randomUUID().toString());
        targetRefGift.setByUserId(userId);
        targetRefGift.setGiftId(giftId);
        targetRefGift.setTargetId(targetId);
        targetRefGift.setGiftName(giftScore.getGiftName());
        targetRefGift.setScore(giftScore.getScore());
        targetRefGift.setCreateTime(now);
        targetRefGift.setByUserName(userName);
        targetRefGift.save();
        //2. 调用IM接口
        String json = JSONObject.toJSONString(targetRefGift);
        StringBuffer sb = new StringBuffer();
        Prop prop = PropKit.use("IMcontext.txt");
        String IM_IP = prop.get("im.ip");
        String IM_PORT = prop.get("im.port");
        // http://zyzhuiyi.xyz:8888 要用域名
        String url = sb.append("http://").append(IM_IP+":").append(IM_PORT).append("/sendGiftToIM").toString();
        try {
            HttpOkUtils.getInstance().postJson(url, json);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return true;
    }

    /**
    *@中软华腾软件系统有限公司,未经授权不得擅自传播
    *@方法描述: 主播查询收到的所有礼物
    *@方法参数描述:
    ** @param targetId
    *@作者: 蒋正午
    *@编辑时间: 2020/05/14  10:11
    *@返回值描述: java.util.List<com.cn.icss.vo.TargetRefGift>
    */
    @Override
    public List<TargetGiftRef> findExceptionalGift(String targetId) {

        List<TargetGiftRef> targetRefGifts = targetRefGiftDao.find("SELECT  *  FROM target_gift_ref WHERE targetId = ? ", targetId);
        return targetRefGifts;
    }
}
